package ebroker.webservice.service;

import ebroker.webservice.ClientBalance;
import ebroker.webservice.data.OMSAPIWebServiceSoap_BindingStub;
import ebroker.webservice.data.WSDSResult;
import ebroker.webservice.data.WSLogonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class EBrokerWebServiceClient {

    private static final Logger logger = LoggerFactory.getLogger(EBrokerWebServiceClient.class);

    private String url;

    private String user;

    private String pass;

    public EBrokerWebServiceClient(String url, String user, String pass) {
        this.url = url;
        this.user = user;
        this.pass = pass;
    }

    /**
     * account 为 null 时，批量查询出所有用户的交易记录
     *
     * @param account
     * @return
     * @throws Exception
     */
    public List<ClientBalance> getBalance(String account) {
        List<ClientBalance> records = null;
        try {
            OMSAPIWebServiceSoap_BindingStub bindingStub = new OMSAPIWebServiceSoap_BindingStub(new URL(url), null);
            bindingStub.setTimeout(500);
            WSLogonResult logonResult = bindingStub.logon(user, pass);
            WSDSResult result = bindingStub.getBalance(user, logonResult.getSessionID(), account);
            String resultContent = result.getDataSet().get_any()[1].toString();
            records = getBalanceFromXml(resultContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return records;

    }

    /**
     * 从 xml 中解析 balance
     *
     * @param content
     * @return
     */
    private List<ClientBalance> getBalanceFromXml(String content) {
        List<ClientBalance> records = new ArrayList<>();
        try {
            int preIndex = 0;
            int fromIndex = 0;
            while (preIndex >= 0 && fromIndex >= 0) {
                int start = content.indexOf("<Client_Balance", fromIndex);
                int end = content.indexOf("</Client_Balance", start);
                preIndex = start;
                fromIndex = end;
                if (start >= 0 && end >= 0) {
                    String singleRecord = content.substring(start, end + "</Client_Balance>".length());

                    int st = singleRecord.indexOf(">");
                    singleRecord = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Client_Balance" + singleRecord.substring(st);
                    JAXBContext context = JAXBContext.newInstance(ClientBalance.class);
                    Unmarshaller unmarshaller = context.createUnmarshaller();
                    ClientBalance re = (ClientBalance) unmarshaller.unmarshal(new StringReader(singleRecord));
                    records.add(re);
                }
            }
        } catch (JAXBException e) {
            logger.error("getRecords from xml error!", e);
        }
        return records;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }
}
